//
//  WBMainViewController.swift
//  Weibo
//
//  Created by cc on 11/07/2017.
//  Copyright © 2017 cc. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {

    //定时器
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        setupCompseButton()
        setupTimer()
        
        //设置新特性视图
        setupNewFeatureViews()
        
        
        //设置代理
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    

    deinit {
        //销毁时钟
        timer?.invalidate()
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    
    
    //代码控制设备方向 竖屏
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    
    // MARK : -监听方法
    @objc private func userLogin(n: Notification) {
        print("用户登录通知 \(n)")
        
        var when = DispatchTime.now()
        
        //判斷n.object是否有值 ->token過期，如果有值就提示用戶重新登錄
        if n.object != nil {
            //設置指示器的漸變樣式
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "登錄超時，請重新登錄")
            
            //修改延遲時間
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            //展现登录控制器  - 通常会和 UINavigationController 连用， 方便返回
            let nav = UINavigationController(rootViewController:  WBOAuthViewController())
            
            self.present(nav, animated: true, completion: nil)
        }
        
    }
    
    
    //撰写微博
    @objc private func composeStatus()  {
        print("write weibo")
        //0 > 判断是否登录
        
        //1 > 实例化视图
        let v = WBComposeTypeView.composeTypeView()
        
        //2 > 显示视图 - 注意闭包的循环引用
        v.show {[weak v] (clsName) in
//            print(clsName)
            //展现撰写微博控制器
            guard let clsName = clsName, let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type else {
                v?.removeFromSuperview()
                return
            }
            
            let vc = cls.init()
            
            let nav = UINavigationController(rootViewController: vc)
            
            //让导航控制器强行更新约束 - 会更新所有子视图的约束
            nav.view.layoutIfNeeded()
            
            self.present(nav, animated: true) {
                v?.removeFromSuperview()
            }
            
           
            
        }
    }
    
    //撰写微博按钮
    private lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}



// MARK: - 新特性视图处理
extension WBMainViewController {
    
    
    /// 设置新特性视图
    private func setupNewFeatureViews() {
       
        //0.判断是否登录
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        //1.如果更新，显示新特性，否则显示欢迎
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        
        //2.添加视图
        view.addSubview(v)
    }
    
    
    /// extension 中可以用计算型属性， 不会占用存储空间
    /// 构造函数，给属性分配空间
    private var isNewVersion: Bool {
        
        //1. 取当前版本号
//        print(Bundle.main.infoDictionary)
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print("当前版本" + currentVersion)
        
        //2. 取保存在 `Document(iTunes 备份)[最理想保存在用户偏好]` 目录中的之前的版本号
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        print("沙盒版本" + sandboxVersion)
//        print(path)
        //3.将当前版本号保存在沙盒
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        //4.返回两个版本号 `是否一致`
        return currentVersion != sandboxVersion
        
    }
}


// MARK: - UITabBarControllerDelegate 代理方法
extension WBMainViewController: UITabBarControllerDelegate {
    
    
    /// 将要选择TabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    
        // 1> 获取控制器在数组中的索引
        let index = (childViewControllers as NSArray).index(of: viewController)
        
        //2 > 判断当前索引是首页， 同时 index 也是首页，重复点击首页按钮
        if selectedIndex == 0 && index == selectedIndex {
            //3. 让表格滚动到顶部
            //a> 获取到控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            // b> 滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            //4. 刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData()
            })
            
            //5. 清除 tabItem的badgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        // 判断目标控制器是否为 UIViewController
        return !viewController.isMember(of: UIViewController.self)
        
    }
}



// MARK: - 时钟相关方法
extension WBMainViewController {
    
    /// 定义时钟
    private func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    
    /// 时钟触发方法
    @objc private func updateTimer() {
        
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        
        WBNetworkManager.shared.unreadCount { (count) in
            
            print("检测到 \(count) 条新微博")
            
            //设置 首页 tarBarItem 的 badgeNumber
            self.tabBar.items?[0].badgeValue =  count > 0 ? "\(count)" : nil
            
            // 设置 App 的 badgeNumber, 从IOS8 之后，要用户授权才能显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}




// extension 类似于 oc中的分类， 在Swift中还可以用来切分代码块
// 可以把相近功能的函数，放在一个 extension中
// 便于代码维护
// 注意： 和oc 分类一样， extension 中不能定义属性

// MARK: - 设置界面
extension WBMainViewController {
    
    //设置撰写按钮
    private func setupCompseButton() {
        
        tabBar.addSubview(composeButton)
        
        //计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        
        // 将向内缩进的宽度
        let w = tabBar.bounds.width / count
        
        //CGRectInsert 正数向内缩进， 负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        print("撰写按钮宽度 \(composeButton.bounds.width)")
        
        //按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
    }
    
    
    //设置所有子控制器
    private func setupChildControllers() {
        
        //0.获取沙盒json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        //判断 data 是否有内容， 如果没有，说明本地沙盒没有文件
        if data == nil {
            //从Bundle 加载data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        // data一定会有内容，反序列化
        // 反序列化转换成数组
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]] else {
            return
        }
        
        
        //在现在的很多应用程序中，界面的创建都信赖 网络的json
/*
        let array:[[String: Any]] = [
            ["clsName": "WBHomeViewController", "title": "首頁", "imageName": "home", "visitorInfo": ["imageName": "","message": "关注一些人,回这里看看有什么惊喜"]],
            ["clsName": "WBMessageViewController", "title": "消息", "imageName": "message_center", "visitorInfo": ["imageName": "visitordiscover_image_message","message": "登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
            ["clsName": "ViewController"],
            ["clsName": "WBDiscoverViewController", "title": "發現", "imageName": "discover", "visitorInfo": ["imageName": "visitordiscover_image_message","message": "登录后，最新、最热微博尽在掌握，不再会与事实潮流擦肩而过"]],
            ["clsName": "WBProfileViewController", "title": "我", "imageName": "profile", "visitorInfo": ["imageName": "visitordiscover_image_profile","message": "登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]],
        ]
        
 */
        
//        
//        //测试数据格式是否正确  - 转换成plist 数据更加直观
//        (array as NSArray).write(toFile: "Users/cc/Desktop/demo.plist", atomically: true)
//        //数组 -> json  序列化
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData).write(toFile: "/Users/cc/Desktop/demo.json", atomically: true)
        
        
        //遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        
        for dict in array! {
            
            arrayM.append(controller(dict: dict))
        }
        
        //设置tabBar的子控制器
        viewControllers = arrayM

    }
    
    
    
    // 使用字典创建一个字控制器
    // - parameters dict: 信息字典[clsName, title, imageName, visitorInfo]
    // - returns  子控制器
    private func controller(dict: [String: Any]) -> UIViewController {
        
        //1. 取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,  //令cls 成为WBBaseViewController
            let visitorDict = dict["visitorInfo"] as? [String : String]
        
        else {
            return UIViewController()
        }
        
        // 2. 创建视图控制器
        let vc = cls.init()
        vc.title = title
        
        //设置控制器的访客信息字典  --  把字典传递给WBBaseViewController
        vc.visitorInfoDictionary = visitorDict  
        
        //3. 设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //4. 设置tabbar 的标题字体(大小)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.orange], for: .highlighted)
        //系统默认是12号字体，修改字体大小，要设置Normal的字体大小
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font: UIFont.systemFont(ofSize:12)], for: UIControlState(rawValue: 0))
        
        //实例化导航控制器的时候，会调用push方法将rootVC压栈
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    }
}
